//
// Created by 21126 on 2023/5/19.
//
#include "U2_S1.h"

unsigned char HT16K33_ADDRESS_S1[4] = {0x74, 0x75, 0x76, 0x77};

unsigned char KEY_values[6];

i2c_addr_def u2_s1_init(int fd)
{
    i2c_addr_def result;
    unsigned char real_slave_address;

    result.flag = 0;

    if (i2c_detect(fd, HT16K33_ADDRESS_S1, sizeof(HT16K33_ADDRESS_S1), &real_slave_address) >= 0)
    {
        result.fd = fd;
        result.addr = real_slave_address;
        result.flag = 1;

        i2c_write_cmd(result.fd, result.addr, SYSTEM_ON_S1);
    }

    return result;
}

int u2_key_trans(i2c_addr_def KEY_addr, unsigned char *key)
{
    int ret;
    ret = i2c_read_bytes(KEY_addr.fd, KEY_addr.addr, KEY_BASE, KEY_values, 6);

    if (!ret)
    {
        if (KEY_values[0] & 0x01) {
            *key = 1;
        } else if (KEY_values[2] & 0x01) {
            *key = 2;
        } else if (KEY_values[4] & 0x01) {
            *key = 3;
        } else if (KEY_values[0] & 0x02) {
            *key = 4;
        } else if (KEY_values[2] & 0x02) {
            *key = 5;
        } else if (KEY_values[4] & 0x02) {
            *key = 6;
        } else if (KEY_values[0] & 0x04) {
            *key = 7;
        } else if (KEY_values[2] & 0x04) {
            *key = 8;
        } else if (KEY_values[4] & 0x04) {
            *key = 9;
        } else if (KEY_values[0] & 0x08) {
            *key = 10;
        } else if (KEY_values[2] & 0x08) {
            *key = 11;
        } else if (KEY_values[4] & 0x08) {
            *key = 12;
        } else {
            ret = -1;
        }
    }
    return ret;
}